About 1670 letters
About 8 minutes
In the process of program development, it is inevitable to deal with some abnormal situations, such as failure to open the file due to being occupied, transmission failure due to network congestion, etc. In order to ensure the normal operation of the program, exception handling is required.
Python uses try
and except
to catch exceptions, and finally
to specify final actions:
except
and finally
are not required, but at least one of them is required except
to handle different types of exceptions try:
try-block # code to run
except 要捕获的异常类型:
except-block # Executed when an exception occurs in the try-block
finally:
finally-block # will be executed no matter what
Example:
try:
10 / 0
except Exception as e: # Catch the exception of type Exception and assign it to e
print("Caught error that is", e)
Exception
is the base class of all exception types and can catch all types of exceptions.
Python uses raise
to generate exceptions:
raise Exception('An error')
Created in 5/15/2025
Updated in 5/21/2025